<template>
  <basic-modal
    v-bind="$attrs"
    :title="modalTitle"
    :confirm-loading="confirmLoading"
    show-confirm
    @confirm="handleConfirm"
  >
    <n-form ref="formRef" :model="modelForm" :rules="rules">
      <n-grid :cols="24" :x-gap="10">
        <n-form-item-gi span="11" label="名称" path="name">
          <n-input placeholder="请输入名称" v-model:value="modelForm.name" />
        </n-form-item-gi>
        <n-form-item-gi span="10" label="唯一编码" path="code">
          <n-input
            :disabled="isEdit"
            placeholder="请输入名称"
            v-model:value="modelForm.code"
          />
        </n-form-item-gi>
        <n-form-item-gi span="3" label="状态" path="status">
          <n-switch
            :checked-value="'1'"
            :unchecked-value="'2'"
            placeholder="请输入名称"
            v-model:value="modelForm.status"
          />
        </n-form-item-gi>
        <n-form-item-gi span="24" label="属性值">
          <n-data-table :columns="valuesTableCols" :data="modelForm.values" />
        </n-form-item-gi>
        <n-gi span="24">
          <n-button
            block
            tertiary
            type="primary"
            @click.stop="handleAddAttrItem"
          >
            <template #icon>
              <AddCircleOutline />
            </template>
            添加属性值
          </n-button>
        </n-gi>
      </n-grid>
    </n-form>
  </basic-modal>
</template>
<script setup lang="ts">
import { v4 as uuidv4 } from "uuid";
import { get, isEmpty } from "lodash-es";
import { reactive, ref, watch, computed, useAttrs, h } from "vue";
import {
  FormInst,
  useMessage,
  NFormItem,
  NInput,
  NButton,
  NIcon,
  NDropdown,
  NSwitch,
} from "naive-ui";
import {
  Trash,
  CreateOutline,
  InformationCircleOutline,
  AddCircleOutline,
} from "@vicons/ionicons5";
import BasicModal from "@/components/normal/basicModal/index.vue";
import {
  createProductAttribute,
  getValuesByAttrId,
  createAttrValue,
  editAttrValue,
  editProductAttribute,
} from "@/api/product/productAttribute.api";
import { IProductAttributeModalProps } from "./props";
import { ActionTypeEnum, InlineDataTypeEnum } from "@/enums/actionTypeEnum";
import {
  ProductAttrValue,
  ProductAttributeDto,
} from "@/types/model/product/dtos/productAttribute.dto";

const dropdownOps = [
  {
    label: "保存",
    key: "confirm",
  },
  {
    label: "取消",
    key: "cancel",
  },
];

const dropdownOps2 = [
  {
    label: "保存",
    key: "confirm",
  },
  {
    label: "删除",
    key: "delete",
  },
];

const rules = {
  name: [
    {
      required: true,
      message: "请输入名称",
      trigger: "change",
    },
  ],
  code: [
    {
      required: true,
      message: "请输入唯一编码",
      trigger: "change",
    },
  ],
};

const valuesTableCols = [
  {
    title: "#",
    type: "index",
    key: "key",
    render: (_: any, index: number) => {
      return h(
        NFormItem,
        {
          showLabel: false,
          showFeedback: false,
        },
        () => index + 1
      );
    },
  },
  {
    title: "名称",
    key: "name",
    render: (row: ProductAttrValue, index: number) => {
      return h(
        NFormItem,
        {
          showLabel: false,
          showFeedback: false,
          path: `values[${index}].name`,
          rule: {
            required: true,
            message: `请输入属性值名称`,
            trigger: ["input", "blur"],
          },
        },
        () =>
          h(NInput, {
            value: row.name,
            disabled: checkValueItemIsDisabled(row),
            placeholder: "请输入属性值名称",
            onUpdateValue(val) {
              row.name = val;
            },
          })
      );
    },
  },
  {
    title: "附加字段1",
    key: "extra1",
    render: (row: ProductAttrValue, index: number) => {
      return h(
        NFormItem,
        {
          showLabel: false,
          showFeedback: false,
          path: `values[${index}].extra1`,
          rule: {
            message: `请输入附加字段1`,
            trigger: ["input", "blur"],
          },
        },
        () =>
          h(NInput, {
            value: row.extra1,
            disabled: checkValueItemIsDisabled(row),
            placeholder: "请输入附加字段1",
            onUpdateValue(val) {
              row.extra1 = val;
            },
          })
      );
    },
  },
  {
    title: "附加字段2",
    key: "extra2",
    render: (row: ProductAttrValue, index: number) => {
      return h(
        NFormItem,
        {
          showLabel: false,
          showFeedback: false,
          path: `values[${index}].extra2`,
          rule: {
            message: `请输入附加字段2`,
            trigger: ["input", "blur"],
          },
        },
        () =>
          h(NInput, {
            value: row.extra2,
            disabled: checkValueItemIsDisabled(row),
            placeholder: "请输入附加字段2",
            onUpdateValue(val) {
              row.extra2 = val;
            },
          })
      );
    },
  },
  {
    title: "状态",
    key: "status",
    render: (row: ProductAttrValue, index: number) => {
      return h(
        NFormItem,
        {
          showLabel: false,
          showFeedback: false,
          path: `values[${index}].status`,
        },
        () =>
          h(NSwitch, {
            checkedValue: "1",
            uncheckedValue: "2",
            value: row.status,
            disabled: checkValueItemIsDisabled(row),
            onUpdateValue(val) {
              row.status = val;
            },
          })
      );
    },
  },
  {
    title: "操作",
    key: "action",
    render: (row: ProductAttrValue) => {
      const isOriginalData = row.dataType === InlineDataTypeEnum.ORIGINAL;
      const isNewData = row.dataType === InlineDataTypeEnum.NEW;
      console.log(`isNewData:${isNewData}`);
      let doms: any[] = [];
      if (isOriginalData) {
        const isDisabled = checkValueItemIsDisabled(row);
        if (isDisabled) {
          doms.push(
            h(
              NButton,
              {
                size: "small",
                strong: true,
                secondary: true,
                onClick: () => handleClickValueEdit(row),
              },
              {
                icon: () =>
                  h(NIcon, {
                    component: CreateOutline,
                  }),
              }
            )
          );
        } else {
          doms.push(
            h(
              NDropdown,
              {
                options: dropdownOps,
                trigger: "hover",
                onSelect: (key) => handleSelect(key, row),
              },
              () =>
                h(
                  NButton,
                  {
                    size: "small",
                    type: "success",
                    strong: true,
                    secondary: true,
                  },
                  {
                    icon: () =>
                      h(NIcon, {
                        component: InformationCircleOutline,
                      }),
                  }
                )
            )
          );
        }
      } else if (isNewData) {
        const isEditAction = props.actionType === ActionTypeEnum.EDIT;
        const isAddAction = props.actionType === ActionTypeEnum.ADD;

        if (isEditAction) {
          doms.push(
            h(
              NDropdown,
              {
                options: dropdownOps2,
                trigger: "hover",
                onSelect: (key) => handleSelect2(key, row),
              },
              () =>
                h(
                  NButton,
                  {
                    size: "small",
                    type: "success",
                    strong: true,
                    secondary: true,
                  },
                  {
                    icon: () =>
                      h(NIcon, {
                        component: InformationCircleOutline,
                      }),
                  }
                )
            )
          );
        } else if (isAddAction) {
          doms.push(
            h(
              NButton,
              {
                size: "small",
                type: "error",
                strong: true,
                secondary: true,
                onClick: () => handleRemoveAttrItem(row),
              },
              {
                icon: () =>
                  h(NIcon, {
                    component: Trash,
                  }),
              }
            )
          );
        }
      }
      return h(
        NFormItem,
        {
          showLabel: false,
          showFeedback: false,
        },
        () => doms
      );
    },
  },
];

const emits = defineEmits(["createSuccess", "editSuccess"]);

const props = withDefaults(defineProps<IProductAttributeModalProps>(), {
  actionType: ActionTypeEnum.ADD,
});

const $attrs = useAttrs();
const message = useMessage();

const formRef = ref<FormInst | null>(null);
const confirmLoading = ref<boolean>(false);
const modelForm = reactive<ProductAttributeDto>({
  id: "",
  name: "",
  code: "",
  status: "1",
  values: [],
});

const isEdit = computed(() => {
  return props.actionType === ActionTypeEnum.EDIT;
});

const modalTitle = computed(() => {
  return isEdit.value ? "编辑属性" : "添加属性";
});

watch(
  () => props.formDetail,
  (newVal) => {
    console.log(newVal);
    if (!isEmpty(newVal)) {
      initEditForm(newVal);
    }
  },
  {
    immediate: true,
    deep: true,
  }
);

watch(
  () => $attrs.show,
  (newVal) => {
    if (!newVal) {
      setTimeout(() => {
        modelForm.name = "";
        modelForm.id = "";
        modelForm.code = "";
        modelForm.status = "1";
        modelForm.values = [];
      }, 200);
    }
  }
);

const handleAddAttrItem = () => {
  let valueItem = {
    id: uuidv4(),
    name: "",
    extra1: "",
    extra2: "",
    dataType: InlineDataTypeEnum.NEW,
    status: "1",
    attributeId: "",
    loading: false,
  };
  const attributeId = get(modelForm, "id");
  if (props.actionType === ActionTypeEnum.EDIT && attributeId) {
    valueItem.attributeId = attributeId;
  }
  modelForm.values.push(valueItem);
};

const handleRemoveAttrItem = (payload: ProductAttrValue) => {
  const id = get(payload, "id") || "";
  if (id) {
    modelForm.values = modelForm.values.filter(
      (item: ProductAttrValue) => item.id !== id
    );
  }
};

const checkValueItemIsDisabled = (valueItem: ProductAttrValue) => {
  let flag = false;
  const dataType = get(valueItem, "dataType");
  const actionType = get(valueItem, "actionType");
  if (
    dataType &&
    dataType === InlineDataTypeEnum.ORIGINAL &&
    actionType === ActionTypeEnum.VIEW
  ) {
    flag = true;
  }
  return flag;
};

const handleEditConfirmAddValue = async (payload: ProductAttrValue) => {
  delete payload.id;
  const res = await createAttrValue(payload);
  console.log(res);
};

const handleSelect = async (key: string, payload: ProductAttrValue) => {
  const dataType = get(payload, "dataType");
  if (dataType === InlineDataTypeEnum.ORIGINAL) {
    if (key === "confirm") {
      // 修改保存
      await editAttrValue(payload);
      await handleGetValueList(modelForm.id as string);
    } else {
      // 点击取消
      payload.name = payload.originName as string;
      payload.extra1 = payload.originExtra1 as string;
      payload.extra2 = payload.originExtra2 as string;
      payload.status = payload.originStatus as string;
      payload.actionType = ActionTypeEnum.VIEW;
    }
  }
};

const handleSelect2 = async (key: string, payload: ProductAttrValue) => {
  const dataType = get(payload, "dataType");
  if (dataType === InlineDataTypeEnum.NEW) {
    if (key === "confirm") {
      // 修改保存
      await handleEditConfirmAddValue(payload);
    } else {
      // 点击删除
      handleRemoveAttrItem(payload);
    }
  }
};

const handleClickValueEdit = (valueItem: ProductAttrValue) => {
  valueItem.actionType = ActionTypeEnum.EDIT;
};

const initEditForm = async (newVal: ProductAttributeDto) => {
  modelForm.id = newVal.id;
  modelForm.name = newVal.name;
  modelForm.status = newVal.status;
  modelForm.code = newVal.code;
  await handleGetValueList(newVal.id as string);
};

const handleGetValueList = async (attrId: string) => {
  let valueList = [];
  if (attrId) {
    try {
      const result = await getValuesByAttrId(attrId);
      valueList = get(result, "result") || [];
    } finally {
    }
  }

  modelForm.values = valueList.map((item: ProductAttrValue) => ({
    id: item.id,
    name: item.name,
    extra1: item.extra1,
    extra2: item.extra2,
    status: item.status,
    originName: item.name,
    originExtra1: item.extra1,
    originExtra2: item.extra2,
    originStatus: item.status,
    dataType: InlineDataTypeEnum.ORIGINAL,
    actionType: ActionTypeEnum.VIEW,
    attributeId: item.attributeId,
    loading: false,
  }));
};

const handleCreateProductAttr = async () => {
  try {
    confirmLoading.value = true;
    await createProductAttribute(modelForm);
    emits("createSuccess");
  } finally {
    confirmLoading.value = false;
  }
};

const handleEditProductAttr = async () => {
  const params = {
    id: modelForm.id,
    name: modelForm.name,
    status: modelForm.status,
  };
  try {
    confirmLoading.value = true;
    await editProductAttribute(params);
    emits("editSuccess");
  } finally {
    confirmLoading.value = false;
  }
};

const handleConfirm = () => {
  formRef.value?.validate(async (errors) => {
    if (errors) {
      message.error("请正确输入表单项");
      return;
    }

    if (props.actionType === ActionTypeEnum.ADD) {
      handleCreateProductAttr();
    } else if (props.actionType === ActionTypeEnum.EDIT) {
      handleEditProductAttr();
    }
  });
};
</script>
<style lang="scss" scoped></style>
